package com.rushb.msg.controller;


import com.rushb.msg.entity.Msg;
import com.rushb.msg.service.MsgService;
import com.rushb.msg.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

/**
 * @program: lizl-project
 * @description:
 * @author: zhaolun.li
 * @create: 2021-06-15 14:20
 **/
@Slf4j
@RestController
@RequestMapping("/msg")
public class MsgController {

    @Autowired
    private MsgService msgService;

    @GetMapping("/sendMag")
    public String sendMag(String phone, String count) {
        log.info("[发送短信] 手机号:{} 发送次数:{}", phone, count);
        if (StringUtils.isNoneBlank(count) && Integer.parseInt(count) > 0) {
            int i = 1;
            while (Integer.parseInt(count) >= i) {
                List<Msg> msgs = msgService.getAll();
                for (Msg msg : msgs) {
                    try {
                        log.info("[发送短信] 发送第{}条短信,地址:{}", i, String.format(msg.getMsg(), phone,phone));
                        HttpClientUtil.httpGet(String.format(msg.getMsg(), phone));
                    } catch (Exception e) {
                        log.info("[发送短信] 发送短信异常,异常信息:{}", e.getMessage());
                        continue;
                    }
                    i++;
                }
            }
        } else if (StringUtils.isNoneBlank(count) && Integer.parseInt(count) == -1){
            while (true) {
                int i = 0;
                List<Msg> msgs = msgService.getAll();
                for (Msg msg : msgs) {
                    log.info("[发送短信] 发送第{}条短信,地址:{}", i, String.format(msg.getMsg(), phone));
                    try {
                        HttpClientUtil.httpGet(String.format(msg.getMsg(), phone));
                    } catch (IOException e) {
                        log.info("[发送短信] 发送短信异常,异常信息:{}", e.getMessage());
                    }
                }
                i++;
            }
        }
        return "手机号:" + phone + ",发送" + count + "次";
    }
}
